package com.yy.wga.user.service.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.wga.common.core.enmus.EUserGrade;
import com.yy.wga.user.service.events.UserSummaryEvent;
import com.yy.wga.user.service.manager.UserManager;
import com.yy.wga.user.service.pojo.UserBaseDO;
import com.yy.wga.user.service.pojo.UserSummaryDO;
import com.yy.wga.user.service.service.UserBaseService;
import com.yy.wga.user.service.service.UserSummaryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: gc
 * @Date: 2024/11/27
 * @Description:
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class UserSummaryListener implements ApplicationListener<UserSummaryEvent> {

    private final UserBaseService userBaseService;
    private final UserManager userManager;
    private final UserSummaryService userSummaryService;

    @Transactional
    public void onApplicationEvent(UserSummaryEvent event) {
        UserBaseDO userBase = userBaseService.getOne(new LambdaQueryWrapper<UserBaseDO>()
                .eq(UserBaseDO::getAppKey, event.getAppKey())
                .eq(UserBaseDO::getId, event.getUserId()));
        if (userBase == null) {
            log.error("用户不存在");
            return;
        }
        // 统计用户结算总金额，升级
        EUserGrade userGrade = EUserGrade.getByType(userBase.getGrade(), userBase.getLevel());
        if (userGrade == null
                || userGrade.getType().equals(EUserGrade.SERVER_1.getType())
                || (userGrade.getType().equals(EUserGrade.SHARE_5.getType()) && userGrade.getLevel().equals(EUserGrade.SHARE_5.getLevel()))) {
            log.info("已经是最高级了，不用升级了");
            return;
        }
        UserSummaryDO userSummary = userSummaryService.getOne(new LambdaQueryWrapper<UserSummaryDO>()
                .eq(UserSummaryDO::getAppKey, event.getAppKey())
                .eq(UserSummaryDO::getUserId, event.getUserId()));
        if (userSummary == null) {
            log.error("没有用户统计数据，为什么会触发结算事件");
            return;
        }
        EUserGrade nextGrade = userGrade;
        while (userSummary.getSaleAmount() >= nextGrade.getNextGrade().getSalesThreshold()) {
            nextGrade = nextGrade.getNextGrade();
        }
        if (nextGrade.equals(userGrade)) {
            log.info("用户当前等级:{}, 未满足{}升级条件，不升级", userGrade.name(), nextGrade.name());
            return;
        }

        // 用户升级
        userManager.upgrade(userBase, nextGrade);
    }
}
